package org.xyf.workflow;


import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.xyf.workflow.service.WorkflowService;

import java.util.*;

@SpringBootApplication
public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);


    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Main.class, args);

        WorkflowService workflowService = context.getBean(WorkflowService.class);

        try {
            run(workflowService);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //测试一个报销流程

    public static void run(WorkflowService workflowService) throws Exception {

        //创建用户于用户组 glfs(格雷福斯)为领导组人员
        workflowService.createUser("xyf","app_xyf");
        workflowService.createUser("glfs","app_xyf");
        workflowService.addUserToGroup("glfs","leader","app_xyf"); //对应xml中的app_xyf_leader

        //部署流程
        String xmlPath = "processes/expense_process.bpmn20.xml";
        workflowService.deploy("app_xyf",xmlPath);

        //启动流程实例
        Map<String, Object> variables = new HashMap<>();
        variables.put("initiator", "xyf"); //对应xml中的${initiator}
        variables.put("amount", 500);
        variables.put("description", "谢银峰需要报销500元打车费用!");
        variables.put("approved", false); // 初始审批状态
        String instanceId = workflowService.startProcessInstance("expenseProcess", "app_xyf", variables);

        //查询用户的active任务列表
        List<Task> taskList = workflowService.queryUserActiveTask("xyf", "app_xyf");

        //提交报销单据
        if(Objects.isNull(taskList) || taskList.isEmpty()) {
            logger.info("{} has no task to deal !","xyf");
            return;
        }
        Optional<Task> optional = taskList.stream()
                .filter(x -> x.getProcessInstanceId().equals(instanceId) && x.getTaskDefinitionKey().equals("submitExpense"))
                .findFirst();

        if(optional.isEmpty()){
            logger.info("{} has no submitExpense task to deal !","xyf");
            return;
        }

        Map<String, Object> data = new HashMap<>();
        data.put("发票1","300");
        data.put("发票2","200");
        workflowService.submitUserTask(optional.get().getId(),"xyf",data);

        //领导审核
        List<Task> leaderTaskList = workflowService.queryUserActiveTask("glfs", "app_xyf");
        if(Objects.isNull(leaderTaskList) || leaderTaskList.isEmpty()) {
            logger.info("{} has no task to deal !","glfs");
            return;
        }
        Optional<Task> leaderOpt = leaderTaskList.stream()
                .filter(x -> x.getProcessInstanceId().equals(instanceId) && x.getTaskDefinitionKey().equals("groupApproval"))
                .findFirst();

        if(leaderOpt.isEmpty()){
            logger.info("{} has no approve task to deal !","glfs");
            return;
        }

        Map<String, Object> reviewData = new HashMap<>();
        reviewData.put("approved",true);//需要对应xml中的变量名
        reviewData.put("comment","单据合法，可以报销");
        workflowService.submitUserTask(leaderOpt.get().getId(),"glfs",reviewData);


        //报销发起人查看最后的审批结果
        List<HistoricProcessInstance> approvedHistory = workflowService.getApprovedHistory("xyf", "app_xyf");

        logger.info("the approvedHistory of xyf is : {}",approvedHistory);


    }
}
